package com.blog.anxinzhu.dubbo.api.graphql;

import com.blog.anxinzhu.dubbo.api.service.HouseResourcesService;
import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;

/**
 * @author chenlin
 * @create 2020-12-05  11:00
 * 将grapQL服务注入到spring容器中
 */
@Component
public class GraphQLProvider {
    private GraphQL graphQL;
    @Autowired
    HouseResourcesService houseResourcesService;

    @Autowired
    private List<MyDataFetcher> myDataFetchers; //注入容器中所有的MyDataFetcher实现类

    @PostConstruct
    public void init() throws FileNotFoundException {
        File file = ResourceUtils.getFile("classpath:anxinzhu.graphqls");
        GraphQLSchema graphQLSchema = buildSchema(file);
        this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();
    }

    private GraphQLSchema buildSchema(File file) {
        TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(file);
        RuntimeWiring runtimeWiring = buildWiring();
        SchemaGenerator schemaGenerator = new SchemaGenerator();
        return schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring);
    }

    private RuntimeWiring buildWiring() {
        return RuntimeWiring.newRuntimeWiring()
                .type("AnxinzhuQuery", builder ->{
                    for (MyDataFetcher myDataFetcher : myDataFetchers) {
                        builder.dataFetcher(myDataFetcher.fieldName(),
                                environment ->
                                        myDataFetcher.dataFetcher(environment));
                    } return builder;
                })
                .build();
    }

    @Bean
    public GraphQL graphQL(){
        return this.graphQL;
    }
}
